package com.seed.uaa.login.impl;

import com.mybatisflex.core.query.QueryChain;
import com.seed.core.exception.UserAuthenticateException;
import com.seed.core.pojo.Account;
import com.seed.core.pojo.LoginDTO;
import com.seed.uaa.login.Login;
import com.seed.uaa.util.EncryptUtil;
import com.seed.uaa.util.LoginCheckUtil;
import com.seed.uaa.util.StpKit;
import com.seed.uaa.web.user.User;

import static com.seed.uaa.web.user.table.UserTableDef.USER;

/**
 * 内部用户用户名登录
 */
public class UserUsernameLogin implements Login {
    @Override
    public void login(Account account, LoginDTO dto) {
        String username = account.getValue();
        User user = QueryChain.of(User.class).where(USER.USERNAME.eq(username)).one();
        LoginCheckUtil.checkLogin(user);

        String rawPassword = dto.getPassword();
        String encrypt = EncryptUtil.encrypt(rawPassword, user.getSalt());
        if(!encrypt.equals(user.getPassword())) {
            throw new UserAuthenticateException("用户名或密码错误");
        }

        StpKit.login(account.getLoginId());
    }
}
